package com.baymax.study.base.controler;

import com.baymax.study.base.domain.dao.ItemEntityDao;
import com.baymax.study.base.domain.entities.ItemEntity;
import com.baymax.study.base.dto.ResultMsg;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * ItemController
 *
 * @author Baymax
 * @since 2024-07-22
 */
@RestController
@RequestMapping("/item")
public class ItemController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ItemController.class);

    @Autowired
    private ItemEntityDao itemEntityDao;

    @GetMapping("/entity")
    @Transactional
    public ResultMsg saveOrUpdateEntity(@RequestParam(value = "itemCode") String itemCode,
        @RequestParam(value = "id", required = false) String id) {
        ItemEntity itemEntity;
        if (StringUtils.isEmpty(id)) {
            // 新增
            itemEntity = new ItemEntity();
            itemEntity.setItemCode(itemCode);
        } else {
            // 更新
            itemEntity = itemEntityDao.queryById(id);
            if (Objects.isNull(itemEntity)) {
                return ResultMsg.buildFailed("id无效");
            }
            itemEntity.setItemCode(itemCode);
        }
        itemEntity = itemEntityDao.saveOrUpdate(itemEntity);
        return ResultMsg.buildSuccess(itemEntity);
    }
}
